<template>
    <div class="login">
        <div class="fix">
            <h3>登录</h3>
            <el-form>
                <el-form-item>
                    <el-input
                        placeholder="请输入用户名"
                        v-model="userinfo.username"
                        clearable
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input
                        v-model="userinfo.password"
                        placeholder="请输入密码"
                        clearable
                        show-password
                    ></el-input>
                </el-form-item>
                <el-form-item class="center">
                    <el-button type="warning" @click="login">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import Vuex from "vuex";
export default {
    data() {
        return {};
    },
    methods: {
        //调取登录的接口 异步操作
        ...Vuex.mapActions({
            userlogin: "user/userlogin_a",
        }),
        //设置登录提醒 同步
        ...Vuex.mapMutations({
            setuserTitle: "user/setuserTitle",
        }),
        login() {
            if (this.userinfo.username == "" || this.userinfo.password == "") {
                this.$message.error("输入不能为空");
                return;
            }
            //点击登录调用登录接口
            this.userlogin(this.userinfo);
            //把登录提示信息设置为空
            this.setuserTitle("");
        },
    },
    computed: {
        ...Vuex.mapGetters({
            userTitle: "user/getuserTitle",
            userinfo: "user/getuserinfo",
            user: "user/getuser",
        }),
    },
    watch: {
        //检测登录是否成功
        userTitle(val) {
            //不为空才执行，防止在设置回去后重新调用
            if (val != "") {
                if (val == "登录成功") {
                    localStorage.setItem("user", JSON.stringify(this.user));
                    //跳转
                    this.$router.push("/index");
                    this.$message.success("登录成功");
                    //重置表单的值为空
                    this.userinfo.password = "";
                    this.userinfo.username = "";
                } else {
                    this.$message.error(val);
                }
            }
        },
    },
};
</script>

<style scoped>
.login {
    width: 100vw;
    height: 100vh;
    background: linear-gradient(#f4a460, #8b4513);
    position: relative;
}
.fix {
    width: 300px;
    padding: 30px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    border-radius: 10px;
}
.login .fix h3 {
    text-align: center;
    margin-bottom: 20px;
}
.login .fix .center {
    text-align: center;
}
</style>
